import { Controller } from 'egg';
// import path from "path";
import { createReadStream } from 'fs';
import { PassThrough } from 'stream';
import compareVersions from 'compare-versions';

export default class VersionController extends Controller {
  public async add() {
    const { ctx } = this;
    await ctx.render('home/add');
  }

  public async new() {
    const { ctx } = this;
    const { version } = ctx.query;
    console.log('new------------------------------');
    console.log('version', version);
    let latestVersion = await this.service.version.getLatest(version.replace(/[\d\.]+/, ''));
    console.log('new latestVersion', latestVersion);
    // 对比现有版本
    // if (latestVersion && latestVersion.version > version) {
    if (latestVersion && compareVersions(latestVersion.version.replace(/T-/i, '').replace(/V/i, ''), version.replace(/T-/i, '').replace(/V/i, '')) > 0) {
      console.log('有最新版本', latestVersion);
      ctx.body = {
        code: 0,
        data: {
          version: latestVersion.version,
          id: latestVersion.id,
          package_path: latestVersion.package_path
        }
      };
    } else {
      console.log('没有最新版本');
      ctx.body = {
        code: 0,
        data: null
      };
    }
  }

  public async download() {
    console.log('download');
    const { ctx } = this;
    const id = ctx.request.body.id || ctx.query.id;
    let data = await this.service.version.getById(id);
    // const buffer = Buffer.from(data.package);
    let fileName = data.version + '.zip';
    console.log(fileName);
    ctx.attachment(fileName);
    ctx.set('Content-Type', 'application/octet-stream');
    ctx.set('Content-Length', data.package.length);
    // ctx.body = data.package;
    const bufferStream = new PassThrough();
    bufferStream.end(data.package);
    ctx.body = bufferStream;
  }

  // public async create2() {
  //   const { ctx } = this;
  //   // const parts = ctx.multipart();
  //   // console.error(parts)
  //   // const version = ctx.request.body.version;
  //   const remark = ctx.request.body.remark;
  //   const files = ctx.request.files;
  //   const autopublic = ctx.request.body.autopublic === '1' || ctx.request.body.autopublic === 1;

  //   console.log('file', files[0]);
  //   console.log('remark', remark);
  //   if (!files || !files[0]) {
  //     await this.handleError('请填写版本号以及上传文件包');
  //   } else {
  //     // 上传逻辑
  //     const file = files[0];
  //     const version = file.filename.replace('aPaaS-IDE-', '').replace('.zip', '');
  //     const versionTag = version.replace(/[\d\.]+/g, '') || '';
  //     const { filepath } = file;
  //     // 1. 判断该版本是否存在
  //     try {
  //       let oldVersonData = await this.service.version.get(version);
  //       if (oldVersonData) {
  //         await this.handleError('上传失败: 该版本已存在');
  //       } else {
  //         let data = await this.readFileFinish(filepath);
  //         let isSuccess = await this.service.version.create(
  //           version,
  //           Buffer.concat(data),
  //           remark,
  //           autopublic
  //         );
  //         console.log(5, isSuccess);
  //         if (autopublic) {
  //           // 1. 推送
  //           // TODO 是不是需要延迟
  //           ctx.app.io.sockets.in(versionTag).emit('version_change', version);
  //           // setTimeout(() => {
  //           // }, 1000);
  //         }
  //         if (isSuccess) {
  //           // await ctx.redirect('home/home');
  //           ctx.set('Location', '../');
  //           ctx.status = 302;
  //           await ctx.render('home/home', {
  //             error: ''
  //           });
  //         } else {
  //           await this.handleError('上传失败');
  //         }
  //         // console.log('filepath', filepath);
  //         // console.log('version', version);
  //         // await ctx.render('home/home');
  //       }
  //     } catch (e) {
  //       // console.error(e);
  //       await this.handleError('上传失败');
  //     }
  //   }
  // }

  public async create() {
    const { ctx } = this;
    // const parts = ctx.multipart();
    // console.error(parts)
    // const version = ctx.request.body.version;
    const remark = ctx.request.body.remark;
    const files = ctx.request.files;
    const autopublic = ctx.request.body.autopublic === '1' || ctx.request.body.autopublic === 1;

    console.log('file', files[0]);
    console.log('remark', remark);
    console.log(autopublic, autopublic);
    if (!files || !files[0]) {
      await this.handleError('请填写版本号以及上传文件包');
    } else {
      // 上传逻辑
      const file = files[0];
      const version = file.filename.replace('aPaaS-IDE-', '').replace('.zip', '');
      const versionTag = version.replace(/[\d\.]+/g, '') || '';
      console.log(versionTag);
      const { filepath } = file;
      // 1. 判断该版本是否存在
      try {
        let oldVersonData = await this.service.version.get(version);
        if (oldVersonData) {
          await this.handleError('上传失败: 该版本已存在');
        } else {
          let data = await this.readFileFinish(filepath);
          let uploadPath = await this.service.version.uploadToOss(version, filepath);
          if (uploadPath) {
            let isSuccess = await this.service.version.create(
              version,
              Buffer.concat(data),
              uploadPath,
              remark,
              autopublic
            );
            if (autopublic) {
              // 1. 推送
              // TODO 是不是需要延迟
              ctx.app.io.sockets.in(versionTag).emit('version_change', version);
            }
            if (isSuccess) {
              // await ctx.redirect('home/home');
              ctx.set('Location', '../');
              ctx.status = 302;
              await ctx.render('home/home', {
                error: ''
              });
            } else {
              await this.handleError('上传失败');
            }
          } else {
            await this.handleError('上传失败: 上传文件到oss出错');
          }
        }
      } catch (e) {
        // console.error(e);
        await this.handleError('上传失败');
      }
    }
  }

  public async issue() {
    return this.create();
  }

  public readFileFinish(filePath: string): Promise<Array<Buffer>> {
    return new Promise((resolve, reject) => {
      let rs = createReadStream(filePath);
      let arr: Array<Buffer> = [];
      rs.on('data', (chunk: Buffer) => {
        arr.push(chunk);
      });
      rs.on('end', async () => {
        // 1写入数据库
        resolve(arr);
      });
      rs.on('error', async (error) => {
        reject(error);
      });
    });
  }

  public async handleError(error: string) {
    const { ctx } = this;
    await ctx.render('home/add', {
      error
    });
  }

  // 发布
  public async publicVersion() {
    const { ctx } = this;
    const { id } = ctx.query;
    const versionData = await this.service.version.getById(+id);
    if (!versionData) {
      throw Error('此id无匹配数据');
    }
    const versionTag = versionData.version.replace(/[\d\.]+/g, '') || '';
    // ctx.app.io.sockets.in(versionTag).emit('version_change', versionData.version);
    // ctx.body = {
    //   code: 0
    // };
    const res = await this.service.version.update(id, {
      public: 1
    });
    if (res) {
      // 发布成功，需要做什么
      // 1. 推送
      console.log('推送', versionTag);
      ctx.app.io.sockets.in(versionTag).emit('version_change', versionData.version);
      // 2. 返回数据
      ctx.body = {
        code: 0
      };
    }
  }
}
